const express = require("express")
const router = express.Router()
const jwt = require("jsonwebtoken")

// 连接数据库
const mongoose = require("mongoose")

// 获取schema
const { Schema } = mongoose
const url = "mongodb://127.0.0.1:27017/shopApp"
mongoose.connect(url).then(() => {
    console.log("链接成功数据库")
})
// 创建数据模版
const userSchema = new Schema({
    username: String,
    password: String,
})
const User = mongoose.model("user", userSchema)

// 注册接口
router.post("/regist", async (req, res, next) => {
    // 获取参数
    let { username, password, tel } = req.body
    // 验证查重
    if (username && password && tel) {
        console.log(username, password)
        const num = await User.find({ username })
        if (num.length != 0) {
            return res.json({ msg: "用户已经存在" })
        } else if (password.length > 10 || password.length < 6) {
            return res.json({ msg: "密码格式不对" })
        } else if (tel.length != 11) {
            return res.json({ msg: "手机号码格式不对" })
        }
    } else {
        console.log("参数错误", username, password, tel)
        res.json({ msg: "注册成功" })
    }
    next()
}, async (req, res) => {
    try {
        const result = await User.create({
            username: req.body.username,
            password: req.body.password,
            tel: req.body.tel
        })
        res.status(200).json({
            msg: "注册成功",
            code: 200,
            data: result
        })
    } catch (err) {
        throw err
    }
})

module.exports = router